/**
 * @description axios 请求封装
 */
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 90000
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// 'application/json'
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const { url } = config
    if (url.indexOf('login') > -1) {
      return config
    } else {
      const token = getToken()
      if (token) {
        config.headers['token'] = token
      }
      return config
    }
  },
  (error) => {
    // 请求发生错误
    console.log(error)
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (response.status === 200) {
      if (res.status !== 0) {
        if (res.status === 20 || res.status === 50) {
          return MessageBox.confirm('用户已过期，请重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        } else if (res.msg === '登录失败：Bad credentials') {
          return Message({
            message: '用户名密码错误，请检查后重新登录!',
            type: 'error',
            duration: 5 * 1000
          })
        } else if (res.status === 1) {
          if (process.env.NODE_ENV === 'development') {
            return Message({
              message: res.msg || 'Error',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          if (process.env.NODE_ENV === 'development') {
            return Message({
              message: res.msg || 'Error',
              type: 'error',
              duration: 5 * 1000
            })
          }
        }
      } else {
        return Promise.resolve(res)
      }
    } else {
      return Promise.reject(new Error(res.msg))
    }
  },
  (error) => {
    if (process.env.NODE_ENV === 'development') {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
